package com.lzb.musicplayer.fragment;

import android.view.View;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.enums.PopupPosition;
import com.lzb.musicplayer.BaseNoModelFragment;
import com.lzb.musicplayer.Content;
import com.lzb.musicplayer.HomeActivity;
import com.lzb.musicplayer.R;
import com.lzb.musicplayer.activity.PlaylistDetailActivity;
import com.lzb.musicplayer.activity.SearchActivity;
import com.lzb.musicplayer.adapter.PlayListAdapter;
import com.lzb.musicplayer.bean.MusicFile;
import com.lzb.musicplayer.bean.PlayListBean;
import com.lzb.musicplayer.databinding.FragmentPlaylistBinding;
import com.lzb.musicplayer.dialog.AddPlaylistDialog;
import com.lzb.musicplayer.dialog.DeleteDialog;
import com.lzb.musicplayer.dialog.MusicEditDialog;
import com.lzb.musicplayer.dialog.PlaylistEditDialog;
import com.lzb.musicplayer.dialog.RenamePlaylistDialog;
import com.lzb.musicplayer.utils.AppSpUtils;
import com.lzb.musicplayer.utils.SaveListUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link PlaylistFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class PlaylistFragment extends BaseNoModelFragment<FragmentPlaylistBinding> implements View.OnClickListener, OnItemClickListener, OnItemChildClickListener {

    private PlayListAdapter playListAdapter;
    private List<PlayListBean> listShow = new ArrayList<>();

    @Override
    protected int onCreate() {
        return R.layout.fragment_playlist;
    }

    @Override
    protected void initView() {
        mDataBinding.ivSearch.setOnClickListener(this);
        mDataBinding.ivAdd.setOnClickListener(this);

        mDataBinding.rvPlayList.setLayoutManager(new GridLayoutManager(mContext, 3));
        playListAdapter = new PlayListAdapter();
        mDataBinding.rvPlayList.setAdapter(playListAdapter);
        playListAdapter.addChildClickViewIds(R.id.ivPlayListItemEdit);
        playListAdapter.setOnItemClickListener(this);
        playListAdapter.setOnItemChildClickListener(this);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ivSearch) {//搜索
            startActivity(SearchActivity.class);
        } else if (id == R.id.ivAdd) {//添加
            showAddPlaylistDialog();
        }
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        PlaylistDetailActivity.selPosition = position;
        startActivity(PlaylistDetailActivity.class);
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        int id = view.getId();
        if (id == R.id.ivPlayListItemEdit) {
            showPlaylistEditDialog(view, playListAdapter.getItem(position).getMusicFileList(), position);
        }
    }

    @Override
    protected void initData() {
        getData();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!isHidden()) {
            getData();
        }
    }

    private void getData() {
        listShow.clear();
        List<PlayListBean> listSp = AppSpUtils.getPlayList();
        if (listSp != null && !listSp.isEmpty()) {
            listShow.addAll(listSp);
            playListAdapter.setList(listSp);
            mDataBinding.rvPlayList.setVisibility(View.VISIBLE);
            mDataBinding.tvPlayNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvPlayList.setVisibility(View.GONE);
            mDataBinding.tvPlayNoData.setVisibility(View.VISIBLE);
        }
    }

    private void showAddPlaylistDialog() {
        AddPlaylistDialog dialog = new AddPlaylistDialog(getContext());
        dialog.setListener(new AddPlaylistDialog.Ilistener() {
            @Override
            public void clickConfirm() {
                getData();
            }
        });
        dialog.show();
    }

    private void showPlaylistEditDialog(View view, List<MusicFile> musicFile, int position) {
        PlaylistEditDialog dialog = new PlaylistEditDialog(mContext);
        BasePopupView basePopupView = new XPopup.Builder(mContext).popupPosition(PopupPosition.Bottom) //手动指定弹窗的位置
                .offsetX(0)//x轴偏移
                .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                .atView(view).hasShadowBg(false) // 去掉半透明背景
                .asCustom(dialog);
        dialog.setListener(new PlaylistEditDialog.Ilistener() {
            @Override
            public void clickItem(int pos) {
                HomeActivity activity = (HomeActivity) getActivity();
                switch (pos) {
                    case 0://播放
                        activity.setFragmentMusicList(musicFile);
                        break;
                    case 1://下一首播放
                        activity.setNextMusic(musicFile);
                        break;
                    case 2://重命名
                        showRenameDialog(position);
                        break;
                    case 3://删除
                        showDeleteDialog(position);
                        break;
                    case 4://保存为文件
                        saveToFile(position);
                        break;
                }
            }
        });
        basePopupView.show();
    }

    private void showRenameDialog(int pos) {
        RenamePlaylistDialog dialog = new RenamePlaylistDialog(mContext);
        dialog.setText(listShow.get(pos).getName());
        dialog.setListener(new RenamePlaylistDialog.Ilistener() {
            @Override
            public void clickConfirm(String text) {
                List<PlayListBean> listSp = AppSpUtils.getPlayList();
                listSp.get(pos).setName(text);
                AppSpUtils.savePlayList(listSp);
                getData();
            }
        });
        dialog.show();
    }

    private void showDeleteDialog(int pos) {
        DeleteDialog dialog = new DeleteDialog(mContext);
        dialog.setText(getString(R.string.playlist_delete_tip));
        dialog.setListener(new DeleteDialog.Ilistener() {
            @Override
            public void clickDelete() {
                List<PlayListBean> listSp = AppSpUtils.getPlayList();
                listSp.remove(pos);
                AppSpUtils.savePlayList(listSp);
                ToastUtils.showShort(getString(R.string.delete_suc));
                getData();
            }
        });
        dialog.show();
    }

    private void saveToFile(int pos) {
        String savePath = PathUtils.getFilesPathExternalFirst() + Content.mySave;
        // 确保目录存在
        FileUtils.createOrExistsDir(savePath);

        // 文件名使用播放列表名称，确保不包含特殊字符
        String fileName = listShow.get(pos).getName().replaceAll("[\\/:*?\"<>|]", "_") + ".m3u";
        String filePath = savePath + "/" + fileName;

        // 构建m3u文件内容
        StringBuilder content = new StringBuilder();
        // m3u文件头
        content.append("#EXTM3U\n");

        // 添加每首歌曲的信息
        for (MusicFile musicFile : listShow.get(pos).getMusicFileList()) {
            // 添加EXTINF行，格式为#EXTINF:时长(秒),标题 - 艺术家
            long durationSeconds = musicFile.getDuration() / 1000; // 转换为秒
            String title = musicFile.getTitle();
            String artist = musicFile.getArtist();
            content.append("#EXTINF:")
                    .append(durationSeconds)
                    .append(",")
                    .append(title)
                    .append(" - ")
                    .append(artist)
                    .append("\n");
            // 添加歌曲文件路径
            content.append(musicFile.getPath()).append("\n");
        }

        // 写入文件
        boolean success = false;
        try {
            // 使用标准Java IO写入文件
            File file = new File(filePath);
            FileWriter writer = new FileWriter(file, false); // false表示覆盖模式
            writer.write(content.toString());
            writer.close();
            success = true;
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 显示保存结果提示
        if (success) {
            ToastUtils.showShort("播放列表已保存至: " + filePath);
        } else {
            ToastUtils.showShort("保存失败，请检查存储权限");
        }
    }

}